package tk0084.dev.google.quiz;

import java.util.Arrays;


/**
 * 盤面を表すクラス
 * @author ohashi
 */
public class Table {

	private final int _col;
	private final int _row;
	private final char[] _chars;
	private int _emptyIndex;

	public static char BLOCK = '=';
	public static char EMPTY = '0';

	public Table(String chars, int row, int col) {
		this._chars = chars.toCharArray();
		this._row = row;
		this._col = col;

		setEmptyIndex(chars.indexOf('0'));
	}

	public Table(char[] chars, int row, int col) {
		this._chars = chars;
		this._row = row;
		this._col = col;

		for(int i = 0; i< _chars.length; i++){
			if(_chars[i] == EMPTY){
				setEmptyIndex(i);
				break;
			}
		}
	}
	
	public boolean canUp() {
		int index = getEmptyIndex() - _col;
		if (index < 0) {
			return false;
		}
		if (_chars[index] == BLOCK) {
			return false;
		}
		return true;
	}

	public boolean canDown() {
		int index = getEmptyIndex() + _col;
		if (index >= _chars.length) {
			return false;
		}
		if (_chars[index] == BLOCK) {
			return false;
		}
		return true;
	}

	public boolean canRight() {
		int emptyIndex = getEmptyIndex();

		if ((emptyIndex + 1) % _col == 0) {
			return false;
		}
		if (_chars[emptyIndex + 1] == BLOCK) {
			return false;
		}

		return true;
	}

	public boolean canLeft() {
		int emptyIndex = getEmptyIndex();

		if ((emptyIndex + 1) % _col == 1) {
			return false;
		}
		if (_chars[emptyIndex - 1] == BLOCK) {
			return false;
		}

		return true;
	}

	public Table moveUp(){
		int mvTo = getEmptyIndex() - _col;
	
		return new Table(moveTo(mvTo), _row, _col);
	}
	
	public Table moveDown(){
		int mvTo = getEmptyIndex() + _col;
	
		return new Table(moveTo(mvTo), _row, _col);
	}
	
	public Table moveRight(){
		int mvTo = getEmptyIndex() + 1;
	
		return new Table(moveTo(mvTo), _row, _col);
	}

	public Table moveLeft(){
		int mvTo = getEmptyIndex() - 1;
	
		return new Table(moveTo(mvTo), _row, _col);
	}
	
	public int getEmptyIndex() {
		return _emptyIndex;
	}

	public void setEmptyIndex(int emptyIndex) {
		this._emptyIndex = emptyIndex;
	}
	
	
	private char[] moveTo(final int mvTo){
		
		char[] charArray = _chars.clone();
		charArray[getEmptyIndex()] = charArray[mvTo];
		charArray[mvTo] = EMPTY;

		return charArray;
	}

	public char[] getChars() {
		return _chars;
	}
	
	@Override
	public boolean equals(Object o){
		Table other = (Table)o;
		
		return Arrays.equals(_chars, other.getChars()) &&
				this.getRow() == other.getRow() &&
				this.getCol() == other.getCol();
	}

	public int getCol() {
		return _col;
	}

	public int getRow() {
		return _row;
	}
}
